package com.teacherprofile.manage.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.teacherprofile.common.annotation.Anonymous;
import com.teacherprofile.common.utils.SecurityUtils;
import com.teacherprofile.manage.config.ChatRedisMemory;
import com.teacherprofile.manage.domain.vo.MessageVO;
import com.teacherprofile.manage.service.ISoftwareCopyrightsService;
import com.teacherprofile.manage.tools.ServiceTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.model.Media;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbacks;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.ai.zhipuai.ZhiPuAiChatOptions;
import org.springframework.ai.zhipuai.api.ZhiPuAiApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
@Slf4j
@RestController
@Api(tags = "智能助手")
@RequestMapping("/agent/ai")
public class AgentController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private ChatRedisMemory chatRedisMemory;

    @ApiOperation(value = "智能助手对话")
    @PreAuthorize("@ss.hasAnyPermi('agent:ai:chat')")
    @RequestMapping(value = "chat", produces = "text/html;charset=utf-8")
    public Flux<String> service(@RequestParam(defaultValue = "你好") String prompt,
                                @RequestParam String chatId,
                                @RequestParam(value = "files", required = false) List<MultipartFile> files) {

        // 1.获取用户信息
        if (files == null || files.isEmpty()) {
            // 没有附件，纯文本聊天
            return textChat(prompt, chatId);
        } else {
            // 有附件，多模态聊天
            return multiModalChat(prompt, chatId, files);
        }

    }

    private Flux<String> multiModalChat(String prompt, String chatId, List<MultipartFile> files) {
        // 1.解析多媒体
        List<Media> medias = files.stream()
                .map(file -> new Media(
                                MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()
                        )
                )
                .toList();
        ZhiPuAiChatOptions options = ZhiPuAiChatOptions.builder()
                .model("GLM-4V-Flash")
                .build();

        ZhiPuAiChatModel zhiPuAiChatModel = new ZhiPuAiChatModel(
                new ZhiPuAiApi("e047bb88077844569470444f28229a74.I7o87P7cUaGmXmtm"), options);
        // 2.请求模型
        return ChatClient.builder(zhiPuAiChatModel)
                .build()
                .prompt()
                .user(p -> p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(new MessageChatMemoryAdvisor(chatRedisMemory, chatId, 10))
                .stream()
                .content();
    }

    private Flux<String> textChat(String prompt, String chatId) {
        return chatClient.prompt()

                .user(prompt)
                .advisors(new MessageChatMemoryAdvisor(chatRedisMemory, chatId, 10))
                .stream()
                .content();
    }



}
